import 'dart:async';
import 'dart:ui';

import 'package:changxindianzishangwu/animation/voice_animation_image.dart';
import 'package:changxindianzishangwu/dao/collect_dao.dart';
import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/model/collect_list_model.dart';
import 'package:changxindianzishangwu/pages/message/chat/video_message_page.dart';
import 'package:changxindianzishangwu/pages/my/collect_note_page.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/show_custom_bottom_sheet.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/common_page.dart';
import 'package:changxindianzishangwu/widget/get_contacts_widget.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_plugin_record/flutter_plugin_record.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_image.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_image_elem.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_sound_elem.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_text_elem.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_video_elem.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

import 'collect_details_page.dart';

///收藏分类列表

class CollectFragmentPage extends StatefulWidget {
  int type;
  bool isSelect;
  bool isSearch;

  CollectFragmentPage({
    Key key,
    this.type,
    this.isSelect = false,
    this.isSearch = false,
  }) : super(key: key);
  _CollectFragmentPageState _collect = _CollectFragmentPageState();

  @override
  _CollectFragmentPageState createState() {
    return this._collect = new _CollectFragmentPageState();
  }

  void searchData(String search) {
    if (_collect != null) {
      _collect.getDataList(searchStr: search, isSearch: true);
    }
  }
}

class _CollectFragmentPageState extends State<CollectFragmentPage> {
  //     with AutomaticKeepAliveClientMixin
  // @override
  // bool get wantKeepAlive => true;

  List<CollectBean> _lists = [];
  List<CollectBean> _selectList = [];
  StringBuffer searchStr = new StringBuffer();
  int page = 0;
  int _position;

  getDataList({String searchStr, bool isSearch = false}) async {
    EasyLoading.show();

    print('---------getDataList${searchStr}');
    CollectListModel _model = !widget.isSearch
        ? await CollectDao.getCollectData(widget.type, page)
        : await CollectDao.collectQueryRequest(page, searchStr);

    EasyLoading.dismiss();
    if (_model.resultCode == 0) {
      toast(_model.resultMsg);
      return;
    }

    if (_refreshController == null) return;
    if (isSearch) {
      _lists.clear();
    }
    if (isRefresh) {
      isRefresh = false;
      _refreshController.refreshFailed();
    }
    if (isLoading) {
      isLoading = false;
      if (_model.data.isEmpty) {
        _refreshController.loadNoData();
      } else
        _refreshController.loadComplete();
    }

    if (mounted)
      setState(() {
        _lists.addAll(_model.data);
      });
  }

  @override
  void initState() {
    if (!widget.isSearch) getDataList();
    _refreshController = RefreshController(initialRefresh: false);
    _initRecordMp3();
    super.initState();
  }

  @override
  void dispose() {
    recordPlugin.dispose();
    super.dispose();
  }

  //是否全选
  bool _isAllSelect = false;

  ///是否在加载更多
  bool isLoading = false;
  bool isRefresh = false;
  RefreshController _refreshController;

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1));
    print("success 刷新");
    // if failed,use refreshFailed()
    page = 0;
    _lists.clear();
    isRefresh = true;
    getDataList();
  }

  void _onLoading() async {
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    print("success 加载");

    if (_lists.length < 3) {
      _refreshController.refreshToIdle();
      return;
    }
    page++;
    isLoading = true;
    getDataList();
  }

  BuildContext _context;

  @override
  Widget build(BuildContext context) {
    _context = context;
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);

    return Container(
      color: AppColor.bg,
      child: isRefresh
          ? CommonPage.loading(() {
              getDataList();
            })
          : Stack(
              children: [
                Padding(
                  padding: EdgeInsets.only(
                      bottom: (widget.isSelect ? height(45) : 0)),
                  child: NotificationListener<ScrollNotification>(
                    onNotification: _scrollListener,
                    child: SmartRefresher(
                      enablePullDown: true,
                      enablePullUp: true,
                      header: MaterialClassicHeader(
                        backgroundColor: AppColor.colorTheme,
                      ),
                      footer: CustomFooter(
                        builder: (BuildContext context, LoadStatus mode) {
                          Widget body;
                          if (mode == LoadStatus.idle) {
                            body = Text("上拉加载");
                          } else if (mode == LoadStatus.loading) {
                            body = CupertinoActivityIndicator();
                          } else if (mode == LoadStatus.failed) {
                            body = Text("加载失败！点击重试！");
                          } else if (mode == LoadStatus.canLoading) {
                            body = Text("松手,加载更多!");
                          } else {
                            body = Text("没有更多数据了!");
                          }
                          return Container(
                            height: _isBottomWidgetShow ? 55.0 : 0.0,
                            child: Center(child: body),
                          );
                        },
                      ),
                      controller: _refreshController,
                      onRefresh: _onRefresh,
                      onLoading: _onLoading,
                      child: CustomScrollView(
                        slivers: [
                          SliverList(
                            delegate: SliverChildBuilderDelegate(
                                (BuildContext content, int index) {
                              return _item(_context, index);
                            }, childCount: _lists.length),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
                widget.isSelect ? _selectDialog() : SizedBox()
              ],
            ),
      // Stack(
      //         children: [
      //           Padding(
      //             padding: EdgeInsets.only(
      //                 bottom: (widget.isSelect ? height(45) : 0)),
      //             child: ListView(
      //               children: List.generate(_lists.length,
      //                   (position) => _item(context, position)).toList(),
      //             ),
      //           ),
      //           widget.isSelect ? _selectDialog() : SizedBox()
      //         ],
      //       ),
    );
  }

  bool _isBottomWidgetShow = false;

  bool _scrollListener(ScrollNotification scrollInfo) {
    final double offset = scrollInfo.metrics.pixels;
    final double maxScrollExtent = scrollInfo.metrics.maxScrollExtent;

    if (maxScrollExtent - offset < 10) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        print("true");
        setState(() {
          _isBottomWidgetShow = true;
        });
      });
      Timer(Duration(milliseconds: 3000), () {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          print("timer");
          setState(() {
            _isBottomWidgetShow = false;
          });
        });
      });
    }

    if (scrollInfo.metrics.axis == Axis.vertical) {
      // print('滚动：${scrollInfo.metrics.pixels}');
      if (scrollInfo.metrics.pixels < 0) {
        return false;
      }
      return true;
    }
    return false;
  }

  ///点击多选后的底部弹框
  Align _selectDialog() {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        color: AppColor.colorGrey245,
        child: Row(
          children: [
            Expanded(
              flex: 1,
              child: TextButton(
                  onPressed: () {
                    setState(() {
                      _isAllSelect = !_isAllSelect;
                    });
                  },
                  child: Text(
                    "全选",
                    style: TextStyle(
                        color: AppColor.colorGrey153, fontSize: sp(16)),
                  )),
            ),
            Expanded(
              flex: 1,
              child: TextButton(
                  onPressed: () {
                    List<V2TimMessage> _someMessage = [];
                    List<CollectBean> _all =
                        _isAllSelect ? _lists : _selectList;
                    if (_all.length == 0) {
                      toast("请选择转发内容");
                      return;
                    }
                    _all.forEach((element) {
                      V2TimMessage _v2Message = _v2(element);
                      _someMessage.add(_v2Message);
                    });
                    print('转发内容   ${json.encode(_someMessage)}');
                    Get.to(GetContactsWidget(
                      someMessage: _someMessage,
                    ));
                  },
                  child: _zfBtn()),
            ),
            Expanded(
              flex: 1,
              child: TextButton(
                  onPressed: () {
                    if (!_isAllSelect && _selectList.length == 0) {
                      toast("请选择删除内容");
                      return;
                    }
                    showCupertinoDialog(
                        context: context,
                        builder: (context) => getDialog(context));
                  },
                  child: Text(
                    "删除",
                    style: TextStyle(color: Colors.red, fontSize: sp(16)),
                  )),
            ),
          ],
        ),
      ),
    );
  }

  _v2(CollectBean element) {
    V2TimMessage _v2Message = V2TimMessage();

    ///1.图片   2.视频   5.文本   4.语音
    switch (element.type) {
      case 1:
        _v2Message.elemType = 3;
        V2TimImage _v2Image = V2TimImage();
        _v2Image.url = element.msg.isNotEmpty ? element.msg : element.url;

        V2TimImageElem _v2ImageElem = V2TimImageElem();
        _v2ImageElem.imageList = [];
        _v2ImageElem.imageList.add(_v2Image);
        _v2Message.imageElem = _v2ImageElem;

        return _v2Message;
      case 2:
        _v2Message.elemType = 5;
        V2TimVideoElem _v2Video = V2TimVideoElem();
        _v2Video.videoUrl = element.msg;
        _v2Video.snapshotUrl = element.url;
        _v2Video.duration = element.fileLength;
        _v2Message.videoElem = _v2Video;
        return _v2Message;
      case 5:
        _v2Message.elemType = 1;
        V2TimTextElem _v2Text = V2TimTextElem();
        _v2Text.text = element.msg;
        _v2Message.textElem = _v2Text;
        return _v2Message;
      case 4:
        _v2Message.elemType = 4;
        V2TimSoundElem _v2Sound = V2TimSoundElem();
        _v2Sound.path = element.msg.isNotEmpty ? element.msg : element.url;
        _v2Sound.duration = element.fileLength;
        _v2Message.soundElem = _v2Sound;
        return _v2Message;
    }
  }

  ///item 背景
  Widget _item(BuildContext context, int position) {
    return Row(
      children: [
        widget.isSelect
            ? IconButton(
                icon: Image.asset(
                  _isAllSelect
                      ? "images/ic_select_ed.png"
                      : _lists[position].isSelect
                          ? "images/ic_select_ed.png"
                          : "images/ic_select_un.png",
                ),
                iconSize: width(18),
                onPressed: () {
                  if (widget.isSelect) {
                    if (mounted) {
                      setState(() {
                        _lists[position].setIsSelect =
                            !_lists[position].isSelect;
                        if (_lists[position].isSelect) {
                          _selectList.add(_lists[position]);
                        } else
                          _selectList.remove(_lists[position]);

                        if (_selectList.length == _lists.length) {
                          _isAllSelect = true;
                        } else
                          _isAllSelect = false;
                      });
                    }
                    return;
                  }
                },
              )
            : SizedBox(),
        Expanded(
          flex: 1,
          child: Container(
            margin: EdgeInsets.only(
                left: width(10), right: width(10), top: width(10)),
            padding: EdgeInsets.all(width(15)),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(5),
            ),
            child: _content(position),
          ),
        ),
      ],
    );
  }

  ///图片文字PDF通用
  Widget _content(int position) {
    CollectBean _bean = _lists[position];
    var date = DateTime.fromMillisecondsSinceEpoch(_bean.createTime * 1000);
    String day = formatDate(date, [yyyy, '-', m, '-', d]);
    return Row(
      children: [
        Expanded(
          flex: 1,
          child: GestureDetector(
            onTap: () {
              if (widget.isSelect) {
                if (mounted) {
                  setState(() {
                    _lists[position].setIsSelect = !_lists[position].isSelect;
                    if (_lists[position].isSelect) {
                      _selectList.add(_lists[position]);
                    } else
                      _selectList.remove(_lists[position]);

                    if (_selectList.length == _lists.length) {
                      _isAllSelect = true;
                    } else
                      _isAllSelect = false;
                  });
                }
                return;
              }

              if (_bean.type == 4) {
                ///语音点击语音容器播放
                return;
              }
              if (_bean.type == 2) {
                ///视频
                Get.to(VideoMessage(
                  url: _bean.msg,
                  snapshotUrl: _bean.url,
                  type: 2,
                ));
              }
              if (_bean.type == 1 || _bean.type == 5) {
                _position=position;
                ///图片文字
                _intentDetail(_bean);
              }
            },
            onLongPress: () {
              _selectAction(position);
            },
            child: Container(
              color: Colors.white,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _typeContent(position),
                  Padding(
                    padding: const EdgeInsets.only(top: 10),
                    child: Text(
                      "$day    ${_bean.remarks == "-1" ? "" : _bean.remarks}",
                      style: TextStyle(
                          color: AppColor.colorGrey153, fontSize: sp(14)),
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
        widget.isSelect
            ? SizedBox()
            : InkWell(
                onTap: () {
                  List<V2TimMessage> _someMessage = [];

                  V2TimMessage _v2Message = _v2(_bean);
                  _someMessage.add(_v2Message);
                  print('转发内容   ${json.encode(_someMessage)}');

                  Get.to(GetContactsWidget(
                    someMessage: _someMessage,
                  ));
                },
                child: _zfBtn(),
              )
      ],
    );
  }

  CupertinoAlertDialog getDialog(context) {
    return CupertinoAlertDialog(
        content: new SingleChildScrollView(
          child: ListBody(
            children: <Widget>[Text("提示"), Text("是否要删除？"), Text("当前选中都将移除收藏夹")],
          ),
        ),
        actions: <Widget>[
          CupertinoDialogAction(
            child: Text("确定"),
            onPressed: () {
              _deleteCollect();
              Navigator.of(context).pop();
            },
          ),
          CupertinoDialogAction(
            child: Text("取消"),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ]);
  }

  ///删除选中收藏
  void _deleteCollect() {
    print('------选中list ${json.encode(_selectList)}');
    List<CollectBean> _beans = _isAllSelect ? _lists : _selectList;
    _beans.forEach((element) {
      _deleteData(element);
    });
  }

  Container _zfBtn() {
    return Container(
      alignment: Alignment.center,
      height: ScreenUtil().setHeight(35),
      width: ScreenUtil().setWidth(50),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6),
        color: Color.fromRGBO(0, 220, 169, 1),
      ),
      child: Text(
        "转发",
        style: TextStyle(color: Colors.white, fontSize: ScreenUtil().setSp(14)),
      ),
    );
  }

  Widget _typeContent(int position) {
    CollectBean _bean = _lists[position];
    switch (_bean.type) {
      case 1: //图片
        return HeadView(
            _bean.msg, ScreenUtil().setWidth(60), ScreenUtil().setWidth(60));
      case 2: //视频
        return _videoImage(position);
      case 5: //文本
        return Text(
          _bean.msg,
          style: TextStyle(color: AppColor.colorDefaultText, fontSize: sp(15)),
          maxLines: 3,
          overflow: TextOverflow.ellipsis,
        );
      case 4: //语音
        return _contentAudios(position);
    }
    return SizedBox();
  }

  _videoImage(int position) {
    var w = MediaQuery.of(context).size.width / 3;

    ///视频分类里 url是视频封面 msg是视频地址
    return Container(
      width: w,
      height: w,
      child: Stack(
        children: [
          HeadView(
            _lists[position].url,
            w,
            w,
          ),
          Align(
            alignment: Alignment.center,
            child: Icon(
              Icons.play_circle_outline_rounded,
              color: Colors.white,
              size: 30,
            ),
          )
        ],
      ),
    );
  }

  ///获取视频略缩图方法
  // _video(int position) {
  //   var w = MediaQuery.of(context).size.width / 3;
  //
  //   return FutureBuilder<String>(
  //       future: getVideoThumbnail(_lists[position].msg),
  //       builder: (context, AsyncSnapshot<String> snapshot) {
  //         print('-------视频${snapshot.connectionState}');
  //         print('-------视频${snapshot.data}');
  //         return Container(
  //           width: w,
  //           height: w,
  //           child: Stack(
  //             children: [
  //               UniversalView().ImageClip(
  //                   filePath:
  //                       snapshot.connectionState == ConnectionState.done &&
  //                               snapshot.data != null
  //                           ? snapshot.data
  //                           : "",
  //                   path: "images/ic_default_video.jpg",
  //                   width: w,
  //                   height: w),
  //               Align(
  //                 alignment: Alignment.center,
  //                 child: Icon(
  //                   Icons.play_circle_outline_rounded,
  //                   color: Colors.white,
  //                   size: 30,
  //                 ),
  //               )
  //             ],
  //           ),
  //         );
  //         // return HeadView(snapshot.connectionState==ConnectionState.done?snapshot.data:"", ScreenUtil().setWidth(60),
  //         //     ScreenUtil().setWidth(60));
  //       });
  // }

  Future<String> getVideoThumbnail(String videopath) async {
    return await VideoThumbnail.thumbnailFile(
      video: videopath,
      thumbnailPath: (await getTemporaryDirectory()).path,
      imageFormat: ImageFormat.JPEG,
      quality: 40,
    );
  }

  /**
   * 播放录音按钮
   */

  _contentAudios(int position) {
    CollectBean audio = _lists[position];
    print('audio${audio.msg}');
    return Container(
      padding: EdgeInsets.only(right: width(15), left: width(10)),
      width: width(120),
      height: width(30),
      decoration: BoxDecoration(
        shape: BoxShape.rectangle,
        borderRadius: BorderRadius.circular(30.0),
        color: AppColor.bg,
      ),
      child: InkWell(
        onTap: () {
          if (_audiosPosition == position) {
            if (mounted) {
              setState(() {
                _lists[_audiosPosition].setISPlaying =
                    !_lists[_audiosPosition].isPlaying;
              });
            }
            pause();
          }
          if (_audiosPosition == -1) {
            _audiosPosition = position;
            if (mounted) {
              setState(() {
                _lists[_audiosPosition].setISPlaying = true;
              });
            }
            playByPath(_lists[_audiosPosition].msg, "url");
          }

          if (_audiosPosition != position) {
            if (_lists[_audiosPosition].isPlaying) {
              print('-----------录音  当前正在播放 不可切换');
              return;
            }
            stopPlay();
            _audiosPosition = position;
            if (mounted) {
              setState(() {
                _lists[_audiosPosition].setISPlaying = true;
              });
            }
            playByPath(_lists[_audiosPosition].msg, "url");
          }
        },
        child: Stack(
          children: [
            Align(
              alignment: Alignment.centerLeft,
              child: VoiceAnimationImage(
                width: width(20),
                height: width(20),
                isStop: audio.isPlaying,
              ),
            ),
            Align(
              alignment: Alignment.centerRight,
              child: Text(
                "${audio.fileLength}s",
                style: TextStyle(
                    fontSize: sp(12), color: AppColor.colorDefaultText),
              ),
            )
          ],
        ),
      ),
    );
  }

  ///暂时不启用PDF布局
  _pdfWidget() {
    return Row(
      children: [
        Icon(
          Icons.picture_as_pdf_rounded,
          size: 40,
          color: Colors.red,
        ),
        Padding(
          padding: const EdgeInsets.only(left: 8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "xxx文件.ppt",
                style: TextStyle(
                    color: AppColor.colorDefaultText, fontSize: sp(15)),
                maxLines: 3,
                overflow: TextOverflow.ellipsis,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 2),
                child: Text(
                  "sizeMb",
                  style:
                      TextStyle(color: AppColor.colorGrey153, fontSize: sp(12)),
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                ),
              )
            ],
          ),
        )
      ],
    );
  }

  ///添加备注/删除弹框
  void _selectAction(int position) async {
    int index = await showDialog(context: context, title: '编辑');
    if (index == 1) {
      ///备注
      Get.to(CollectNotePage(_lists[position])).then((value) {
        if (value == null) return;
        setState(() {
          _lists[position].remarks = value;
        });
      });
    }
    if (index == 2) {
      await CollectDao.collectDelete(_lists[position].emojiId).then((value) {
        if (value == 0) {
          toast("删除失败");
          return;
        }
        if (value == 1) {
          toast("删除成功");
          setState(() {
            _lists.removeAt(position);
          });
        }
      });
    }
  }

  _deleteData(CollectBean bean) async {
    await CollectDao.collectDelete(bean.emojiId).then((value) {
      if (value == 0) {
        toast("删除失败");
        return;
      }
      if (value == 1) {
        _selectList.remove(bean);
        _lists.remove(bean);
      }
      if (_selectList.length == 0) {
        toast("删除成功");
        setState(() {});
      }
    });
  }

  Future<int> showDialog({
    @required BuildContext context,
    @required String title,
  }) {
    return showCustomBottomSheet(
        context: context,
        title: title,
        cancelTextColor: AppColor.colorDialog,
        children: [
          actionItem(
              context: context,
              index: 1,
              title: '添加备注',
              color: AppColor.colorDialog),
          actionItem(
              context: context,
              index: 2,
              title: '删除',
              isLastOne: true,
              color: Colors.red),
        ]);
  }

  /**
   * -----------------------录音 start------------------------------------------------
   */
  FlutterPluginRecord recordPlugin = new FlutterPluginRecord();
  int _audiosPosition = -1;

  ///初始化语音录制的方法
  void _initRecordMp3() async {
    recordPlugin.initRecordMp3();
    recordPlugin.responsePlayStateController.listen((data) {
      print("播放路径   " + data.playPath);
      print("播放状态   " + data.playState);
      if (data.playState == "complete" || data.playState == "false") {
        if (mounted) {
          setState(() {
            _lists[_audiosPosition].setISPlaying = false;
            _audiosPosition = -1;
          });
        }
      }
    });
  }

  ///播放指定路径录音文件  url为iOS播放网络语音，file为播放本地语音文件
  void playByPath(String path, String type) {
    print('-----------AAAA  path${path} ');
    print('-----------AAAA  type${type} ');
    recordPlugin.playByPath(path, type);
  }

  ///暂停|继续播放
  void pause() {
    recordPlugin.pausePlay();
  }

  void stopPlay() {
    recordPlugin.stopPlay();
  }

  void _intentDetail(CollectBean _bean) async {
    var back = await Get.to(CollectDetailsPage(_bean));
    if (back == null) return;
    if (back is bool) {
      setState(() {
        _lists.remove(_bean);
      });
    }
    if(back is String){
      setState(() {
        _lists[_position].remarks = back;
      });
    }
  }

/**
 * -----------------------录音 end------------------------------------------------
 */
}
